package com.example.JavaWebApi.core.mybatisplusextention;
/**
 * @author: 杨泽
 * @create: 2022-03-08 10:09
 */

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

/**
 *@program: wsbgt7-web-api
 *@description: 切换数据库类帮助
 *@author: 杨泽
 *@create: 2022-03-08 10:09
 */
@Slf4j
public class SwitchDatabaseHelper {
    /**
     * Description:
     * @param ProductId 产品id
	 * @param supplier 需要执行的委托
     * @return TResult 返回结果预期类型
     * @author 杨泽
     * @date 2022/3/8 17:02
     */
    @SneakyThrows
    public static <TResult> TResult switchData(int ProductId, Supplier<TResult> supplier){
        DataBaseType dataBaseType=DataBaseType.getTypeByCode(ProductId);
        DynamicDataSourceContextHolder.push(dataBaseType.getName());
        try{
            TResult result =supplier.get();
            return result;
        }
       catch (Exception e){
            log.error(e.getMessage());
            throw new Error("切换数据库失败!");
       }
        finally {
            DynamicDataSourceContextHolder.poll();
        }
    }
}